<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>心灵树洞 - 管理员后台</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
    <style>
        /* 管理员后台专用样式 */
        .admin-container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
            background: #f8f9fa;
            min-height: 100vh;
        }
        
        .admin-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 30px;
            border-radius: 15px;
            margin-bottom: 30px;
            text-align: center;
            box-shadow: 0 8px 32px rgba(0,0,0,0.1);
        }
        
        .admin-title {
            font-size: 2.2em;
            margin: 0 0 10px 0;
            font-weight: 600;
        }
        
        .admin-subtitle {
            font-size: 1.1em;
            opacity: 0.9;
            margin: 0;
        }
        
        .filter-section {
            background: white;
            padding: 25px;
            border-radius: 15px;
            margin-bottom: 25px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.08);
        }
        
        .filter-title {
            font-size: 1.3em;
            margin-bottom: 15px;
            color: #333;
            font-weight: 600;
        }
        
        .filter-controls {
            display: flex;
            gap: 15px;
            align-items: center;
            flex-wrap: wrap;
        }
        
        .filter-select {
            padding: 12px 15px;
            border: 2px solid #e1e5e9;
            border-radius: 8px;
            font-size: 1em;
            background: white;
            min-width: 200px;
            transition: all 0.3s ease;
        }
        
        .filter-select:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }
        
        .filter-btn {
            padding: 12px 25px;
            background: #667eea;
            color: white;
            border: none;
            border-radius: 8px;
            font-size: 1em;
            cursor: pointer;
            transition: all 0.3s ease;
            font-weight: 500;
        }
        
        .filter-btn:hover {
            background: #5a67d8;
            transform: translateY(-2px);
        }
        
        .clear-btn {
            background: #6c757d;
        }
        
        .clear-btn:hover {
            background: #5a6268;
        }
        
        .stats-section {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-bottom: 25px;
        }
        
        .stat-card {
            background: white;
            padding: 20px;
            border-radius: 12px;
            text-align: center;
            box-shadow: 0 4px 20px rgba(0,0,0,0.08);
            transition: transform 0.3s ease;
        }
        
        .stat-card:hover {
            transform: translateY(-5px);
        }
        
        .stat-number {
            font-size: 2.5em;
            font-weight: bold;
            color: #667eea;
            margin-bottom: 5px;
        }
        
        .stat-label {
            color: #666;
            font-size: 0.9em;
        }
        
        .messages-section {
            background: white;
            border-radius: 15px;
            overflow: hidden;
            box-shadow: 0 4px 20px rgba(0,0,0,0.08);
        }
        
        .messages-header {
            background: #f8f9fa;
            padding: 20px 25px;
            border-bottom: 1px solid #e9ecef;
        }
        
        .messages-title {
            font-size: 1.4em;
            margin: 0;
            color: #333;
            font-weight: 600;
        }
        
        .message-item {
            padding: 25px;
            border-bottom: 1px solid #f0f0f0;
            transition: background-color 0.3s ease;
        }
        
        .message-item:hover {
            background-color: #f8f9fa;
        }
        
        .message-item:last-child {
            border-bottom: none;
        }
        
        .message-meta {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
            flex-wrap: wrap;
            gap: 10px;
        }
        
        .message-category {
            display: inline-block;
            padding: 6px 12px;
            border-radius: 20px;
            font-size: 0.85em;
            font-weight: 500;
            color: white;
        }
        
        .category-学业压力 { background: #ff6b6b; }
        .category-人际关系 { background: #4ecdc4; }
        .category-家庭烦恼 { background: #45b7d1; }
        .category-未来迷茫 { background: #96ceb4; }
        .category-其他情绪 { background: #feca57; }
        
        .message-time {
            color: #666;
            font-size: 0.9em;
        }
        
        .message-content {
            background: #f8f9fa;
            padding: 20px;
            border-radius: 10px;
            line-height: 1.6;
            color: #333;
            white-space: pre-wrap;
            word-wrap: break-word;
        }
        
        .no-messages {
            text-align: center;
            padding: 60px 20px;
            color: #666;
        }
        
        .no-messages-icon {
            font-size: 4em;
            margin-bottom: 20px;
        }
        
        .logout-section {
            text-align: center;
            margin-top: 30px;
            padding: 20px;
        }
        
        .logout-btn {
            padding: 12px 30px;
            background: #dc3545;
            color: white;
            border: none;
            border-radius: 8px;
            font-size: 1em;
            cursor: pointer;
            transition: all 0.3s ease;
            text-decoration: none;
            display: inline-block;
        }
        
        .logout-btn:hover {
            background: #c82333;
            transform: translateY(-2px);
        }
        
        .delete-btn {
            padding: 6px 12px;
            background: #dc3545;
            color: white;
            border: none;
            border-radius: 6px;
            font-size: 0.85em;
            cursor: pointer;
            transition: all 0.3s ease;
            margin-left: 10px;
        }
        
        .delete-btn:hover {
            background: #c82333;
            transform: translateY(-1px);
        }
        
        .message-actions {
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        @media (max-width: 768px) {
            .admin-container {
                padding: 15px;
            }
            
            .filter-controls {
                flex-direction: column;
                align-items: stretch;
            }
            
            .filter-select, .filter-btn {
                width: 100%;
            }
            
            .message-meta {
                flex-direction: column;
                align-items: flex-start;
            }
        }
    </style>
</head>
<body>
    <div class="admin-container">
        <!-- 管理员页面头部 -->
        <header class="admin-header">
            <h1 class="admin-title">🛡️ 心灵树洞管理后台</h1>
            <p class="admin-subtitle">用心守护每一份倾诉，用爱陪伴每一个心灵</p>
        </header>

        <!-- 统计信息 -->
        <div class="stats-section">
            <div class="stat-card">
                <div class="stat-number">{{ messages|length }}</div>
                <div class="stat-label">总留言数</div>
            </div>
            <div class="stat-card">
                <div class="stat-number">{{ categories|length }}</div>
                <div class="stat-label">问题分类</div>
            </div>
            <div class="stat-card">
                <div class="stat-number">
                    {% set today_count = messages|selectattr('timestamp')|list|length %}
                    {{ today_count }}
                </div>
                <div class="stat-label">今日留言</div>
            </div>
        </div>

        <!-- 筛选功能 -->
        <div class="filter-section">
            <h3 class="filter-title">📊 筛选留言</h3>
            <form method="GET" class="filter-controls">
                <select name="category" class="filter-select">
                    <option value="">全部分类</option>
                    {% for category in categories %}
                    <option value="{{ category }}" {% if current_filter == category %}selected{% endif %}>
                        {{ category }}
                    </option>
                    {% endfor %}
                </select>
                <button type="submit" class="filter-btn">🔍 筛选</button>
                <a href="{{ url_for('admin') }}" class="filter-btn clear-btn">🔄 清除筛选</a>
            </form>
        </div>

        <!-- 留言列表 -->
        <div class="messages-section">
            <div class="messages-header">
                <h2 class="messages-title">
                    💬 学生留言
                    {% if current_filter %}
                    <span style="color: #667eea;">（{{ current_filter }}）</span>
                    {% endif %}
                </h2>
            </div>

            {% if messages %}
                {% for message in messages %}
                <div class="message-item" id="message-{{ message.id }}">
                    <div class="message-meta">
                        <div>
                            <span class="message-category category-{{ message.category }}">
                                {{ message.category }}
                            </span>
                            <span style="color: #999; font-size: 0.8em;">ID: {{ message.id }}</span>
                        </div>
                        <div class="message-actions">
                            <span class="message-time">
                                📅 {{ message.timestamp.strftime('%Y-%m-%d %H:%M') }} (北京时间)
                            </span>
                            <button class="delete-btn" onclick="deleteMessage({{ message.id }})">
                                🗑️ 删除
                            </button>
                        </div>
                    </div>
                    <div class="message-content">{{ message.content }}</div>
                </div>
                {% endfor %}
            {% else %}
                <div class="no-messages">
                    <div class="no-messages-icon">📭</div>
                    <h3>暂无留言</h3>
                    <p>
                        {% if current_filter %}
                        当前筛选条件下没有找到相关留言
                        {% else %}
                        还没有学生提交倾诉内容
                        {% endif %}
                    </p>
                </div>
            {% endif %}
        </div>

        <!-- 退出登录 -->
        <div class="logout-section">
            <button onclick="logout()" class="logout-btn">🚪 退出登录</button>
        </div>
    </div>

    <script>
        // 删除留言功能
        function deleteMessage(messageId) {
            if (confirm('确定要删除这条留言吗？删除后无法恢复！')) {
                // 显示加载状态
                const deleteBtn = event.target;
                const originalText = deleteBtn.innerHTML;
                deleteBtn.innerHTML = '⏳ 删除中...';
                deleteBtn.disabled = true;
                
                // 发送删除请求
                fetch(`/admin/delete/${messageId}`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    }
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        // 删除成功，移除DOM元素
                        const messageElement = document.getElementById(`message-${messageId}`);
                        if (messageElement) {
                            messageElement.style.transition = 'opacity 0.3s ease';
                            messageElement.style.opacity = '0';
                            setTimeout(() => {
                                messageElement.remove();
                                // 检查是否还有留言，如果没有则显示空状态
                                const messagesSection = document.querySelector('.messages-section');
                                const remainingMessages = messagesSection.querySelectorAll('.message-item');
                                if (remainingMessages.length === 0) {
                                    location.reload(); // 重新加载页面以显示"暂无留言"状态
                                }
                            }, 300);
                        }
                        alert('留言删除成功！');
                    } else {
                        alert('删除失败：' + data.message);
                        // 恢复按钮状态
                        deleteBtn.innerHTML = originalText;
                        deleteBtn.disabled = false;
                    }
                })
                .catch(error => {
                    console.error('删除请求失败:', error);
                    alert('删除失败，请检查网络连接后重试');
                    // 恢复按钮状态
                    deleteBtn.innerHTML = originalText;
                    deleteBtn.disabled = false;
                });
            }
        }

        // 退出登录功能
        function logout() {
            if (confirm('确定要退出登录吗？')) {
                // 清除浏览器保存的认证信息
                fetch('/admin', {
                    method: 'GET',
                    headers: {
                        'Authorization': 'Basic ' + btoa('invalid:invalid')
                    }
                }).then(() => {
                    // 重定向到首页
                    window.location.href = '/';
                }).catch(() => {
                    // 如果请求失败，直接重定向
                    window.location.href = '/';
                });
            }
        }

        // 自动刷新功能（每5分钟刷新一次）
        setInterval(function() {
            if (confirm('检测到新的留言，是否刷新页面查看？')) {
                location.reload();
            }
        }, 300000); // 5分钟 = 300000毫秒

        // 页面加载完成后的初始化
        document.addEventListener('DOMContentLoaded', function() {
            console.log('管理员后台加载完成');
            
            // 添加键盘快捷键支持
            document.addEventListener('keydown', function(e) {
                // Ctrl + R 刷新页面
                if (e.ctrlKey && e.key === 'r') {
                    e.preventDefault();
                    location.reload();
                }
                
                // Esc 键退出登录
                if (e.key === 'Escape') {
                    logout();
                }
            });
        });
    </script>
</body>
</html>